package com.example.clock.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import com.example.clock.entity.Attend;
import com.example.clock.entity.AttendVo;
import com.example.clock.service.AttendService;
import com.example.clock.util.AttendExcelListener;
import com.example.clock.vo.AttendExcel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Controller
@RequestMapping("/attend")
public class AttendController {

    private static final Logger logger = LoggerFactory.getLogger(AttendController.class);

    @Autowired
    private AttendService attendService;

    //上下班打卡
    @PostMapping("/clocktodo")
    public String clock(String userName, String clockTime, Model model) throws UnsupportedEncodingException {
        try {
            LocalDateTime date = LocalDateTime.now();
            if (clockTime != null && !clockTime.isEmpty()) {
                if (clockTime.length() <= 16) {
                    clockTime = clockTime + ":00";
                }
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                date = LocalDateTime.parse(clockTime, formatter);
            }
            if (userName == null || userName.isEmpty()) {
                userName = "username";
            }
            String msg = attendService.clock(userName, date);
            model.addAttribute("msg", msg);
            msg = URLEncoder.encode(msg, "UTF-8");
            userName = URLEncoder.encode(userName, "UTF-8");
            return "redirect:/attend/getClockList?msg=" + msg + "&userName=" + userName;
        }catch (Exception e) {
            logger.error("打卡失败", e);
            return "redirect:/attend/getClockList?msg=" + "打卡失败" + "&userName=" + userName;
        }
    }

    @GetMapping("/getClockList")
    public String getClockList(Integer month, String userName, Integer page, Integer limit, Model model, String msg) throws UnsupportedEncodingException, ParseException {
        model.addAttribute("msg", msg);
        model.addAttribute("userName", userName);
        try {
            if (page == null) {
                page = 1;
            }
            if (limit == null) {
                limit = 10;
            }
            LocalDate sTime;
            LocalDate eTime;
            LocalDate now = LocalDate.now();
            if (month == null) {
                month = now.getMonthValue();
                sTime = now.withDayOfMonth(1);
                eTime = now.withDayOfMonth(LocalDate.now().lengthOfMonth());
            } else {
                sTime = now.withMonth(month).withDayOfMonth(1);
                eTime = now.withMonth(month).withDayOfMonth(LocalDate.now().withMonth(month).lengthOfMonth());
            }
            AttendVo data = attendService.getClockList(userName, sTime, eTime, page, limit);
            List<String> estimatedTimeOfDismissal = attendService.getEstimatedTimeOfDismissal(userName);
            model.addAttribute("estimatedTimeOfDismissal", estimatedTimeOfDismissal);
            model.addAttribute("data", data);
            model.addAttribute("monthValue", month);
        }catch (Exception e){
            logger.error("获取打卡列表失败", e);
        }
        return "clock";
    }
    @GetMapping("/toClockEdit")
    public String toClockEdit(Integer month, String userName, Integer page, Integer limit, Model model, String msg) throws UnsupportedEncodingException, ParseException {
        getClockList(month, userName, page, limit, model, msg);
        return "clockEdit";
    }

    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response,String userName) {
        try {
            attendService.exportExcel(response,userName);
        }catch (Exception e){
            logger.error("导出失败", e);
        }

    }
    @PostMapping("/importExcel")
    public String importExcel(@RequestParam("file") MultipartFile file,Model model,String userName) {
        try {
            if (!file.isEmpty()) {
                try {
                    AttendExcelListener attendExcelListener = new AttendExcelListener(userName);
                    EasyExcel.read(file.getInputStream(), AttendExcel.class, attendExcelListener).sheet().doRead();
                    // 对导入的数据进行处理
                    List<Attend> attendList = attendExcelListener.getAttendList();
                    if (!attendList.isEmpty()) {
                        attendService.saveBatch(attendList);
                    }
                    model.addAttribute("msg", "导入成功");
                } catch (IOException e) {
                    model.addAttribute("msg", "导入失败");
                    throw new RuntimeException(e);
                }
            } else {
                model.addAttribute("msg", "请选择文件");
            }
        }catch (Exception e){
            logger.error("导入失败", e);
        }
        return "recordOperate";
    }
    @PostMapping("/updateClock")
    @ResponseBody
    public int editClock(Attend attend) {
        try {
            return attendService.editClock(attend);
        }catch (Exception e){
            logger.error("编辑失败", e);
            return 0;
        }
    }

    @PostMapping("/deleteClock")
    @ResponseBody
    public int deleteClock(@RequestParam("ids") List<Integer> ids) {
        try {
            attendService.deleteClock(ids);
            return 1;
        } catch (Exception e) {
            logger.error("删除失败", e);
            return 0;
        }
    }
}
